package com.grapecity.forguncy.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipPackager {
    public static void zipPaths(ZipConfigs[] sourcePaths, String zipFilePath) throws IOException {
        FileOutputStream fos = new FileOutputStream(zipFilePath);
        ZipOutputStream zos = new ZipOutputStream(fos);
        for (ZipConfigs sourcePath : sourcePaths) {
            File file = new File(sourcePath.path);
            if (file.exists()) {
                if (file.isDirectory()) {
                    addFolderToZip(file, "", zos, sourcePath,true);
                } else {
                    addFileToZip(file, "", zos, sourcePath);
                }
            }
        }
        zos.close();
        fos.close();
    }

    private static void addFileToZip(File file, String parentFolder, ZipOutputStream zos, ZipConfigs zipConfigs) throws IOException {

        if(zipConfigs.includeAbsPath !=null) {
            if (!zipConfigs.includeAbsPath.contains(file.toPath().toString())) {
                return;
            }
        }
        if (!zipConfigs.excludeFileNames.isEmpty()) {
            List<String> invalidNames = Arrays.stream(zipConfigs.excludeFileNames.split("\\|")).toList();

            if (invalidNames.contains(file.getName())) {
                return;
            }
        }
        FileInputStream fis = new FileInputStream(file);
        zos.putNextEntry(new ZipEntry(parentFolder + file.getName()));

        byte[] buffer = new byte[1024];
        int length;
        while ((length = fis.read(buffer)) > 0) {
            zos.write(buffer, 0, length);
        }

        fis.close();
        zos.closeEntry();
    }

    private static void addFolderToZip(File folder, String parentFolder, ZipOutputStream zos, ZipConfigs zipConfigs,boolean isFirstLayer) throws IOException {
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                String _parentFolder = zipConfigs.packageToRoot ? "" : parentFolder + folder.getName() + "/";
                if(zipConfigs.ignoreFirstLayer && isFirstLayer) {
                    _parentFolder = "";
                }
                if (file.isDirectory()) {
                    addFolderToZip(file, _parentFolder, zos, zipConfigs,false);
                } else {
                    addFileToZip(file, _parentFolder, zos, zipConfigs);
                }
            }
        }
    }
}
